﻿// 版权所有 (c) 2021-2024 duanzt

using Admin.NET.Core.Service;
using Admin.NET.Plugin.ViewFace.Service.FaceSet.Dto;
using System.ComponentModel;

namespace Admin.NET.Plugin.ViewFace.Service;
[ApiDescriptionSettings(ViewFaceConst.GroupName, Order = 101)]
public class FaceGroupService : IDynamicApiController, ITransient
{
    //
    private readonly UserManager _userManager;
    private readonly SqlSugarRepository<FaceUserGroup> _faceUserGroupRep;

    public FaceGroupService(UserManager userManager,
        SqlSugarRepository<FaceUserGroup> faceUserGroupRep)
    {
        _userManager = userManager;
        _faceUserGroupRep = faceUserGroupRep;
    }

    /// <summary>
    /// 获取分组分页列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取分组分页列表")]
    public async Task<SqlSugarPagedList<FaceUserGroup>> Page(FaceUserGroupInput input)
    {
        return await _faceUserGroupRep.AsQueryable()
            .WhereIF(!_userManager.SuperAdmin, u => u.TenantId == _userManager.TenantId) // 若非超管，则只能操作本租户的角色
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code))
            .OrderBy(u => u.Id)
            .ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 添加用户组
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task AddUseGroup(AddFaceUserGroupInput input)
    {
        if (await _faceUserGroupRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code))
            throw Oops.Oh(ViewFaceEnum.D1001);

        await _faceUserGroupRep.InsertAsync(input.Adapt<FaceUserGroup>());
    }

    /// <summary>
    /// 更新用户组
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    [DisplayName("更新用户组")]
    public async Task UpdateUserGroup(UpdatePosInput input)
    {
        if (await _faceUserGroupRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code && u.Id != input.Id))
            throw Oops.Oh(ViewFaceEnum.D1001);

        var sysPos = await _faceUserGroupRep.GetByIdAsync(input.Id) ?? throw Oops.Oh(ViewFaceEnum.D1002);

        await _faceUserGroupRep.AsUpdateable(input.Adapt<FaceUserGroup>()).IgnoreColumns(true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除用户组
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task DeleteUserGroup(DeleteFaceUserGroupInput input)
    {
        await _faceUserGroupRep.DeleteAsync(u => u.Id == input.Id);
    }
}
